package org.alex.samples.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.alex.samples.model.CommonMessageResultVO;
import org.alex.samples.model.UserJDBC;
import org.alex.samples.service.IUserJdbcService;
import org.alex.samples.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class UserJdbcController {
	
	@Autowired
	private IUserJdbcService userJdbcService;
	
	@Autowired
	private LocaleResolver localeResolver;
	
	@Autowired
	private MessageSource messageSource;
	
	@RequestMapping(value="/changeLocale")
	public String changeLocale(HttpServletRequest request,HttpServletResponse response,String localeType){
		if("en_US".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.US);
		}else if("zh_CN".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/userJdbcs";
	}
	
	
	
	
// 获取所有当前学生关联的科目的后台方法
	@ResponseBody
	@RequestMapping(value="getAllSubject")
	public Map<String,Object> getAllSubject(String userId){
		Map<String,Object> resultMap=new HashMap<String,Object>();
		resultMap.put("allSubject",userJdbcService.getAllSubject());//获取所有科目，包括没关联的
		resultMap.put("selectedSubject",userJdbcService.getAllSubjectByUser(userId));//获取所有已关联的科目
		//System.out.println(teacherService.getAllUserBySubject(subjectId));
		return resultMap;
	}
	
	
	//保存修改 管理学生科目
		@ResponseBody
		@RequestMapping(value="saveStudentSubjects")
		public Map<String, Object> saveStudentSubjects(@RequestParam(name="studentSubjects[]")String[] studentSubjects,String userId ){
			Map<String,Object> resultMap=new HashMap<String,Object>();
			resultMap.put("success",false);
			List<String> list=new ArrayList<String>();
			for(String subject : studentSubjects){
				list.add(subject);
			}
			try{
				//传到service，有service来处理
				userJdbcService.saveStudentSubject(list,userId);
				resultMap.put("success", true);
			}catch(Exception e){
				e.printStackTrace();
			}
			return resultMap;
		}
	

	
	
	//查询全部学生方法
		@RequestMapping("/userJdbcs")
		public String userJdbcs(Model model){
			List<UserJDBC> list=userJdbcService.findAllUserJdbcs();
			
			model.addAttribute("edit", messageSource.getMessage("page.index.edit", null,LocaleContextHolder.getLocale()));
			model.addAttribute("userJdbcList", list);
			return "userJdbc/userJdbcList";
		}
		
		
	//新增学生方法
		@RequestMapping(value="/addUserJdbc",method=RequestMethod.GET)
		public String toAdd(Model model){
			model.addAttribute("userJDBC", new UserJDBC());
			return "userJdbc/addUserJdbc";
		}
		
		@RequestMapping(value="/addUserJdbc" ,method=RequestMethod.POST)
		public String add(RedirectAttributes redirectAttributes,@Validated UserJDBC userJDBC,BindingResult result){
			if(result.hasErrors()){
				return "userJdbc/addUserJdbc";
			}
			try{
				userJdbcService.createUserJdbc(userJDBC);
				redirectAttributes.addFlashAttribute("message", "添加成功。");
				
			}catch(Exception e){
				e.printStackTrace();
				return "error";
				
			}
			return "redirect:/userJdbcs";
		}
		
		
		
		//修改方法
		@RequestMapping(value="/editUserJdbc/{userId}", method=RequestMethod.GET)
		public String toEdit(Model model,@PathVariable String userId){
			UserJDBC userJDBC=userJdbcService.getUserJdbcById(userId);
			model.addAttribute("userJDBC",userJDBC);
			return "userJdbc/editUserJdbc";
		}
		
		@RequestMapping(value="/editUserJdbc/{userId}", method=RequestMethod.POST)
		public String edit(RedirectAttributes redirectAttributes,UserJDBC userJDBC,@PathVariable String userId){
			try{
				
				userJDBC.setUserId(userId);
				userJdbcService.editUserJdbc(userJDBC);
				redirectAttributes.addFlashAttribute("message", "修改成功.");
			}catch(Exception e){
				e.printStackTrace();
				return "error";
			}
			return "redirect:/userJdbcs";
		}
		
		
		//测试删除方法  （添加一个dele.jsp,完善删除功能，提示是否删除）
		@RequestMapping(value="/deleUserJdbc/{userId}",method=RequestMethod.GET)
		public String toDele(Model model,@PathVariable String userId){
			UserJDBC userJDBC=userJdbcService.getUserJdbcById(userId);
			model.addAttribute("userJDBC",userJDBC);
			return "userJdbc/deleUserJdbc";
		}
		
		@RequestMapping(value="/deleUserJdbc/{userId}",method=RequestMethod.POST)
		public String delete(RedirectAttributes redirectAttributes,@PathVariable String userId){
			try{
				userJdbcService.deleteUserJdbc(userId);
//				redirectAttributes.addFlashAttribute("message", "删除成功.");
			}catch(Exception e){
				redirectAttributes.addFlashAttribute("message", "删除失败.");
				e.printStackTrace();
				return "error";
			}
			return "redirect:/userJdbcs";
		}
			

//批量增加学生信息		
@ResponseBody
@RequestMapping(value="/uploadFile")
public CommonMessageResultVO uploadFile(@RequestParam(value="uploadFile") MultipartFile[] uploadFile,HttpSession session,Model model){
	//System.out.println("控制器");
	
	CommonMessageResultVO resultVO =new CommonMessageResultVO();
	MultipartFile uploadSimpleFile=uploadFile[0];
	String fileName=uploadSimpleFile.getOriginalFilename();
	
	//获取文件的后缀名
	String postfix=fileName.substring(fileName.lastIndexOf("."));
	Map<String,String> messageMap=new HashMap<String,String>();
	
	try{
		//判断文件类型只能是xlsx,xls
		if(ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix) || ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
			userJdbcService.saveStudentByExcel(uploadSimpleFile.getInputStream(),postfix);
			resultVO.setSuccess(true);
		}else{
			messageMap.put("message", "文件格式不正确。");
			resultVO.setMessageMap(messageMap);
		}
	}catch(Exception e){
		e.printStackTrace();
		messageMap.put("message", "批量导入失败！");
		resultVO.setMessageMap(messageMap);
	}
	return resultVO;
}
	
}
